package com.pjs.tdd;

import static com.pjs.tdd.NegativeTransaction.negativeTransaction;
import static com.pjs.tdd.PositiveTransaction.positiveTransaction;

import java.util.HashSet;

public abstract class AbstractAccount implements Account {
	
	private final AccountIdentifier accountIdentifier;
	private Money balance;
	private final TransactionCollection transactions;
	
	public AbstractAccount(final AccountIdentifier accountIdentifier,final Money startingBalance){
		this.accountIdentifier=accountIdentifier;
		this.balance=startingBalance;
		this.transactions=new TransactionCollectionImpl(new HashSet<Transaction>());
	}

	@Override
	public AccountType type() {
		return accountIdentifier.type();
	}
	
	@Override
	public Money balance(){
		return this.balance;
	}
	
	@Override
	public void processTransaction(Transaction... transactions) {
		for(Transaction transaction : transactions){
			this.balance=transaction.apply(this.balance());
			this.transactions.add(transaction);
		}
	}
	
	@Override
	public void rollbackTransaction(Transaction... transactions) {
		for(Transaction transaction : transactions){
			Transaction reverseTransaction=null;
			switch(transaction.type()){
				case negative :
					reverseTransaction=positiveTransaction(transaction.transactionAmount());
					break;
				case positive :
					reverseTransaction=negativeTransaction(transaction.transactionAmount());
					break;
			}
			this.balance=reverseTransaction.apply(this.balance());
			this.transactions.add(transaction);
		}
	}
	
	@Override
	public int transactionsProcessed(){
		return this.transactions.size();
	}

	@Override
	public int number() {
		return this.accountIdentifier.id();
	}
	
}
